package com.banciyuan.bcywebview.biz.post.write.series;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.banciyuan.bcywebview.R;
import com.banciyuan.bcywebview.api.NovelApi;
import com.banciyuan.bcywebview.base.activity.BaseActivity;
import com.banciyuan.bcywebview.base.helper.ActionbarHelper;
import com.banciyuan.bcywebview.base.helper.LoadingHelper;
import com.banciyuan.bcywebview.base.helper.data.UserDataHelper;
import com.banciyuan.bcywebview.biz.post.write.WriteArticleActivity;
import com.banciyuan.bcywebview.utils.http.HttpUtils;
import com.banciyuan.bcywebview.utils.http.StringRequestParam;
import com.banciyuan.bcywebview.utils.http.VolleyQueue;
import com.banciyuan.bcywebview.utils.intent.gotoUtil;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import com.banciyuan.bcywebview.utils.http.BcyPair;

import org.json.JSONObject;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import de.greenrobot.daoexample.model.MySeriesItem;

/**
 * Created by hy on 2015/12/31.
 */
public class SelectSeriesActivity extends BaseActivity implements ActionbarHelper.OnActionCallbacks, View.OnClickListener {
    private static final int CREATE_SERIES = 100;
    private static final int GO_POSTWRITE = 101;
    private View mProgressbarView;
    private LoadingHelper mProgressbarHelper;
    private View mActionBarView;
    private ActionbarHelper mActionbarHelper;
    private ListView mListView;
    private RequestQueue mQueue;
    private SelectSeriesAdapter mAdapter;
    private List<MySeriesItem> list = new ArrayList<MySeriesItem>();
    private int page = 1;
    private boolean mLastItemVisible = false;
    private boolean loading = false;
    private boolean end_flag = false;
    private View rootView;
    private String work = "";
    private String tag = "";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        rootView = View.inflate(this, R.layout.selectseries_layout, null);
        setContentView(rootView);
        initArgs();
        initUi();
        initProgressbar();
        initActionbar();
        initAction();
        initData();
    }

    @Override
    protected void initUi() {
        mListView = (ListView) findViewById(R.id.listView);
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View header = layoutInflater.inflate(R.layout.createseries_header, mListView, false);
        mListView.addHeaderView(header);
        mAdapter = new SelectSeriesAdapter(this, list);
        mListView.setAdapter(mAdapter);
    }

    @Override
    protected void initActionbar() {
        mActionBarView = findViewById(R.id.base_action_bar);
        mActionbarHelper = new ActionbarHelper(this, mActionBarView);
        mActionbarHelper.setTitle(getString(R.string.select_series));
        mActionbarHelper.setActionCallbacks(this);
    }

    @Override
    protected void initProgressbar() {
        mProgressbarHelper = new LoadingHelper(rootView);
        mProgressbarHelper.setActionCallbacks(new LoadingHelper.OnProgressCallbacks() {
            @Override
            public void onActionClick(int id) {
                int state = mProgressbarHelper.getState();
                if (state == LoadingHelper.PROGRESS_STATE_NODATA)
                    return;
                mProgressbarHelper.onLoading();
                initData();
            }
        });
        mProgressbarHelper.onLoading();
    }

    @Override
    protected void initArgs() {
        mQueue = VolleyQueue.getRquest(this);
        Intent intent = getIntent();
        work = intent.getStringExtra(gotoUtil.INTENT_VALUE_ONE);
        tag = intent.getStringExtra("tags");
    }


    @Override
    protected void initAction() {
        findViewById(R.id.rl_create_series).setOnClickListener(this);
        findViewById(R.id.tv_empty_create_series).setOnClickListener(this);
        mListView.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int state) {
                if (state == AbsListView.OnScrollListener.SCROLL_STATE_IDLE && mLastItemVisible) {
                    if (!loading) {
                        if (!end_flag) {
                            page++;
                            loading = true;
                            initData();
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
                mLastItemVisible = (totalItemCount > 0) && (firstVisibleItem + visibleItemCount >= totalItemCount - 1);
            }
        });
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                position = position - 1;
                if (position >= 0 && position < list.size()) {
                    MySeriesItem seriesItem = list.get(position);
                    Intent intent = new Intent(SelectSeriesActivity.this, WriteArticleActivity.class);
                    intent.putExtra(gotoUtil.INTENT_VALUE_ONE, seriesItem.getTitle());
                    intent.putExtra(gotoUtil.INTENT_VALUE_TWO, seriesItem.getCount());
                    intent.putExtra(gotoUtil.INTENT_VALUE_THREE, seriesItem.getType());
                    intent.putExtra(gotoUtil.INTENT_VALUE_FOUR, seriesItem.getWork());
                    intent.putExtra(gotoUtil.INTENT_VALUE_FIVE, seriesItem.getWns_id());
                    intent.putExtra(gotoUtil.INTENT_VALUE_SIX, seriesItem.getCover());
                    intent.putExtra("tags", tag);
                    intent.putExtra("tag_array", (Serializable) seriesItem.getTags());
                    startActivityForResult(intent, GO_POSTWRITE);
                }
            }
        });
    }

    @Override
    protected void initData() {
        List<BcyPair> paramsList = new ArrayList<BcyPair>();
        paramsList.add(new BcyPair(HttpUtils.TOKEN, UserDataHelper.getInstance(this).getToken()));
        paramsList.add(new BcyPair(HttpUtils.INDEX_P, page + ""));
        final HashMap<String, String> params = HttpUtils.getData(paramsList);
        String url = HttpUtils.BASE_URL + NovelApi.getMynovelset();
        Response.Listener succ = new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                try {
                    JSONObject result = new JSONObject(s);
                    Object status = result.get(HttpUtils.UPLOAD_STATUS);
                    String st = status.toString();
                    if (st.equals("1")) {
                        Gson gson = new Gson();
                        List<MySeriesItem> tempList = gson.fromJson(result.getString(HttpUtils.UPLOAD_DATA),
                                new TypeToken<List<MySeriesItem>>() {
                                }.getType());
                        if (tempList.isEmpty()) {
                            if (page == 1)
                                mProgressbarHelper.onNodata("", true);
                            else
                                mProgressbarHelper.onSuccess();
                            end_flag = true;
                        } else {
                            processData(tempList);
                            mProgressbarHelper.onSuccess();
                        }
                        loading = false;
                    } else {
                        mProgressbarHelper.onFailed();
                        loading = false;
                    }
                } catch (Exception e) {
                    mProgressbarHelper.onFailed();
                    loading = false;
                }
            }
        };

        Response.ErrorListener error = new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                mProgressbarHelper.onFailed();
                loading = false;
            }
        };
        StringRequestParam stringRequest = new StringRequestParam(Request.Method.POST, url, params, succ, error);
        mQueue.add(stringRequest);
    }

    private void processData(List<MySeriesItem> tempList) {
        if (page == 1) {
            list.clear();
        }
        list.addAll(tempList);
        mAdapter.notifyDataSetChanged();
    }

    @Override
    public void onBackClick() {
        finish();
    }

    @Override
    public void onActionClick(int id) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.rl_create_series:
            case R.id.tv_empty_create_series:
                Intent intent = new Intent(this, CreateSeriesActivity.class);
                intent.putExtra(gotoUtil.INTENT_VALUE_ONE, work);
                intent.putExtra("tags", tag);
                startActivityForResult(intent, CREATE_SERIES);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == CREATE_SERIES) {
            if (resultCode == RESULT_OK) {
                setResult(RESULT_OK);
                finish();
            }
            if (resultCode == RESULT_CANCELED) {
                end_flag = false;
                page = 1;
                initData();
            }
        }
        if (requestCode == GO_POSTWRITE && resultCode == RESULT_OK) {
            setResult(RESULT_OK);
            finish();
        }
    }
}
